package com.tes;

import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.entity.text.ChangeableText;

public class CountDownTimer implements IUpdateHandler {

	// timer given
	private float timerSeconds;
	// interval
	private float timerInterval;
	// time passed
	private float timeElapsed;
	// last call
	private float lastCall;
	// is timer on
	private boolean isRunning;
	// text
	private ChangeableText cText;

	public CountDownTimer(float timerSeconds, float timerInterval,
			ChangeableText cText) {

		this.timerSeconds = timerSeconds;
		this.timerInterval = timerInterval;
		this.timeElapsed = 0;
		this.lastCall = 0;
		this.isRunning = true;
		this.cText = cText;
	}

	@Override
	public void onUpdate(float pSecondsElapsed) {
		timeElapsed += pSecondsElapsed;

		if (isRunning) {
			if (timeElapsed - lastCall >= timerInterval) {
				float timeRemain = timerSeconds - timeElapsed;
				cText.setText(timeRemain + "");
			}

			if (timeElapsed > timerSeconds) {
				this.cancel();
			}
		}
	}

	@Override
	public void reset() {
		this.timeElapsed = 0;
		this.lastCall = 0;
	}

	public void cancel() {
		this.isRunning = false;
	}

}
